package com.hup.utils.algorithm;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * 图像label;
 * 目前只实现了居中显示图像
 */
public class ImageLabel extends JLabel {

    private Image background;
    private int iWidth, iHeight;

    public void setBackground(BufferedImage background) {
        this.background = background;
        if (background == null) {
            iWidth = iHeight = 0;
        } else {
            iWidth = background.getWidth(null);
            iHeight = background.getHeight(null);
        }
        repaint();
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        if (background != null) {
            int pWid = getWidth();
            int pHei = getHeight();
            g.setColor(Color.WHITE.darker());
            g.fillRect(0, 0, pWid, pHei);

            double rParent = pWid / (pHei + 0d);
            double rImage = iWidth / (iHeight + 0d);
            int bgWidth, bgHeight;
            if (rParent < rImage) {
                //上下空白
                bgWidth = pWid;
                bgHeight = (int) (bgWidth / rImage);
            } else {
                //左右空白
                bgHeight = pHei;
                bgWidth = (int) (bgHeight * rImage);
            }
            int paddingX = (pWid - bgWidth) / 2;
            int paddingY = (pHei - bgHeight) / 2;
            g.drawImage(background,
                    paddingX, paddingY, bgWidth, bgHeight,
                    null);
        }
    }
}
